package org.cheniy.trigger.job;

import lombok.extern.slf4j.Slf4j;
import org.cheniy.domain.task.model.entity.TaskEntity;
import org.cheniy.domain.task.service.ITaskService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author cheniy
 * @description 发送MQ消息任务队列
 * @create 2025/3/19 22:18
 */
@Slf4j
@Component ()
public class SendMessageTaskJob {

    @Resource
    private ITaskService taskService;
    @Resource
    private ThreadPoolExecutor executor;


    @Scheduled (cron = "0/30 * * * * ? ")
    public void exec() {
        try {
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            log.info("查询task中失败数据，size：{}",taskEntities.size());
            for (TaskEntity taskEntity:taskEntities){
                executor.execute(() -> {
                    try {
                        taskService.sendMessage(taskEntity);
                        taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                    } catch (Exception e) {
                        log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                        taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                    }
                });

            }

        }catch (Exception e){
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        }
    }
}
